package com.qfedu.openplateform.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.qfedu.openplateform.cache.service.CacheService;
import com.qfedu.openplateform.common.constans.ExceptionDict;
import com.qfedu.openplateform.common.entity.BaseResultBean;
import com.qfedu.openplateform.gateway.config.ApplicationContextHolder;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *  登陆 过滤器 主要用于鉴权 token
 *
 * @author lileijian
 * @create 2021-12-05 0:42
 */
public class LoginFilter implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 拿到 token
        String token = request.getParameter("token");
        // 判断 token 不为空
        if (!StringUtils.isEmpty(token)){
            // 解析token  去和 redis 做对比
            Claims body = Jwts.parser().setSigningKey("meiyoumima".getBytes()).parseClaimsJws(token).getBody();
            // 解析得到用户信息
            String subject = body.getSubject();
            System.out.println("subject = " + subject);

            // 去redis 比对  需要从容器 CacheService
            CacheService cacheService = ApplicationContextHolder.getApplicationContext().getBean(CacheService.class);
            String tokenFromRedis = cacheService.getFromRedis("token-" + subject);

            //对比判断
            if (token.equals(tokenFromRedis)){
                return true;
            }

        }

        // 返回json 数据 重新登陆
        response.setContentType("application/json;charset=utf-8");
        BaseResultBean bean = new BaseResultBean();
        bean.setCode(ExceptionDict.UNLOGIN);
        bean.setMsg("请求检查token");
        try {
            response.getWriter().println(JSON.toJSONString(bean));
        } catch (JsonProcessingException ex) {
            ex.printStackTrace();
        }

        return false;
    }
}
